package com.bf.electroplating.config.exception;

import com.bf.electroplating.pojo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Slf4j
@ResponseBody
@ControllerAdvice
public class WebExceptionHandler {

	@ExceptionHandler ( Exception.class )
	public ResultVO < String > handleException( Exception e ) {
		log.error( "系统记录到异常" , e );
		if (e.getMessage().equals("物料库存不足！")){
			return ResultVO.fail(e.getMessage());
		}
		return ResultVO.fail( "系统错误，请联系管理员处理" );
	}


	@ResponseStatus ( HttpStatus.BAD_REQUEST )
	@ExceptionHandler ( value = MethodArgumentNotValidException.class )
	public ResultVO < String > handleMethodArgumentNotValidException( MethodArgumentNotValidException e ) {
		log.error( "实体参数校验异常" , e );
		BindingResult bindingResult = e.getBindingResult();
		ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().orElse( new ObjectError( "" ,
				"" ) );
		return ResultVO.fail( objectError.getDefaultMessage() );
	}

}
